import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useRootData } from "../../tools/useRootData";

const Detail: React.FC = () => {
  const params = useParams();
  const [book, setBook] = useState<any>({});

  const container = {
    padding: "20px",
    margin: "20px",
    width: "500px",
    borderRadius: "8px",
    backgroundColor: "beige",
  };

  const { getSelectBook, addBook } = useRootData((store) => ({
    getSelectBook: store.bookStore.getSelectBook,
    addBook: store.cartStore.addBook,
  }));

  useEffect(() => {
    if (params.id && typeof params.id === "string") {
      const book = getSelectBook(params.id);
      setBook(book);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [params.id]);

  return (
    <div style={container}>
      <h1>书名：{book.name}</h1>
      <h3>简介：{book.description}</h3>
      <h3>价格：{book.price}￥</h3>
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <button onClick={() => addBook(book)}>加入购物车＋</button>
      </div>
    </div>
  );
};
export default Detail;
